package com.api.syh56.shengyunhui.controller;

import com.api.syh56.shengyunhui.common.*;
import com.api.syh56.shengyunhui.entity.*;
import com.api.syh56.shengyunhui.entity.vo.WAGParamVO;
import com.api.syh56.shengyunhui.entity.vo.WAGParamVOAndQuote;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.mapper.WayBillMapper;
import com.api.syh56.shengyunhui.properties.AliSmsProperties;
import com.api.syh56.shengyunhui.service.*;
import com.api.syh56.shengyunhui.util.AliSpeechUtil;
import com.api.syh56.shengyunhui.websocket.ChatServer;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;


import static com.api.syh56.shengyunhui.util.CommonUtil.getLongFromRequestBody;
@Slf4j
@RestController
@RequestMapping("waybill")
public class WayBillController {

    @Autowired
    private WayBillMapper wayBillMapper;

    @Autowired
    private WayBillService wayBillService;

    @Autowired
    private WAGParamService wagParamService;

    @Autowired
    private UserService userService;

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private QuoteService quoteService;

    @Autowired
    private SystemMessageService systemMessageService;

    @Autowired
    private AliSpeechUtil aliSpeechUtil;

    @Autowired
    private RoutesService routesService;


    @Autowired
    private CouponDetService couponDetService;

    @Autowired
    private WaybillRouteService waybillRouteService;

    @Autowired
    private ChatServer chatServer;

    private final ReentrantLock lock = new ReentrantLock();

    /**
     * 货主端  (我的运单) 运单状态
     * @param yearmonth
     * @param waybillStatus
     * @return
     */
    @PostMapping("/shiper/waybillPage")
    public CommonResult<Map<String,List<WAGParamVO>>> shiperWaybillPage(@RequestParam @DateTimeFormat(pattern = "yyyyMM") String yearmonth,
                                                                  @RequestParam Short waybillStatus) {

        Map<String, List<WAGParamVO>> stringListMap = wayBillService.waybillRecentList(yearmonth, waybillStatus, Constants.Role.SHIPER);

        // 返回封装好的结果
        return CommonResult.success(stringListMap);
    }

    /**
     * 司机端  (我的运单) 运输状态
     * @param pageSize
     * @param pageNum
     * @param deliveryStatus
     * @return
     */

    @GetMapping("/driver/waybillPage")
    public CommonResult<Object> DriverWaybillPage(@RequestParam(defaultValue = "5") Integer pageSize,
                                                                        @RequestParam(defaultValue = "1") Integer pageNum,
                                                                        @RequestParam Short deliveryStatus) {
        Page<Object> objectPage = new Page<>(pageNum, pageSize);
        CommonPage<WAGParamVOAndQuote> QWAGpage = new CommonPage<>();
        CommonPage<WAGParamVO> WAGpage = new CommonPage<>();

        if (deliveryStatus == Constants.DeliveryStatus.QUOTE) {
            Page<WAGParamVOAndQuote> wagParamVOAndQuotePage = quoteService.quoteRecentPage(objectPage, deliveryStatus);
            QWAGpage = CommonPage.restPage(wagParamVOAndQuotePage);
            // 返回封装好的结果
            return CommonResult.success(QWAGpage);
        } else {
            Page<WAGParamVO> wagParamVOPage = wayBillService.waybillRecentPage(objectPage, deliveryStatus, Constants.Role.DRIVER);
            WAGpage = CommonPage.restPage(wagParamVOPage);
            return CommonResult.success(WAGpage);
        }


    }


    /**
     * 删除运单(连带删除绑定的临时地址和货物表项)
     * @param id
     * @return
     */
    @PostMapping("/deleteById")
    public CommonResult deleteWaybill(@RequestParam Long id){
        wayBillService.deleteWaybill(id);
        return CommonResult.success(null);
    }

    /**
     * 货主端 取消运单(只更新运单状态)
     * @param id
     * @return
     */
    @PostMapping("/shiper/cancelWaybillById")
    public CommonResult cancelWaybill(@RequestParam Long id){
        wayBillService.shipCancelWaybill(id);
        chatServer.onMessage(Constants.webSocket.WAYBILL.toString());
        return CommonResult.success(null);
    }

    /**
     * 货主端发布货源（包含收发地址、货源等详细信息）
     * @param wagParam
     * @return
     */
    @PostMapping("/shiper/insertInfodetail")
    @Transactional
    public CommonResult<Object> insertInfodetail(@RequestBody WAGParam wagParam){
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        //获取当前用户信息
        //设置发件方姓名、联系电话
//        tmpAddress shipArea = wagParam.getShip_area();
//        shipArea.setAddressLocation(wagParam.getShip_area().getAddressLocation());
//        shipArea.setContactName(user.getTrueName());
//        shipArea.setTelephone(user.getTelephone());
//        shipArea.setUid(user.getId());
//        wagParam.setShip_area(shipArea);

        //插入运单
        Waybill waybill = wagParamService.insertWAG(wagParam);


        //发送消息给 收发地点匹配的专线用户
        systemMessageService.SendMessageToDriverWhenSameAddress(waybill);

        //添加运单专线匹配表
        QueryWrapper<Waybill> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Waybill::getGoodsId,waybill.getGoodsId());
        Waybill one = wayBillService.getOne(wrapper);
        waybillRouteService.insetByWid(one.getId());
        chatServer.onMessage(Constants.webSocket.WAYBILL.toString());
        return CommonResult.success(waybill);
    }



    /**
     * 运单详细信息（运单id）
     * @param id
     * @return
     */
    @PostMapping("/selectInfodetail")
    public CommonResult<WAGParamVO> selectInfodetail(@RequestParam Long id){
        WAGParamVO wagParamVO = wayBillService.showOneInfo(id);
        return CommonResult.success(wagParamVO);
    }



    /**
     * 管理端查看所有运单
     */
    @PostMapping("admin/selectAll")
    public CommonResult<Object> selectAll(){
        List<Waybill> waybills = wayBillService.list();
        return CommonResult.success(waybills);
    }

    /**
     * 首页货源显示（货主端只显示自己发布的货物 、司机端查看最近运单（未确认报价）
     */
    @PostMapping("driver/recentWaybills")
    public CommonResult<CommonPage<WAGParamVO>> driverRecentWaybills(@RequestParam(defaultValue = "5") Integer pageSize,
                                                     @RequestParam(defaultValue = "1") Integer pageNum, Short role){
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        System.out.println("recentWaybills"+ uid);
        QueryWrapper<Waybill> waybillQueryWrapper = new QueryWrapper<>();

        //货主端只显示自己发布的货物
        if(Constants.Role.SHIPER.equals(role)){
            waybillQueryWrapper.lambda().eq(Waybill::getShiperId,uid);
        }else if(Constants.Role.DRIVER.equals(role)){
            QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
            routesQueryWrapper.lambda().eq(Routes::getUid,uid);
            List<Routes> routes = routesService.list(routesQueryWrapper);

            List<String> routesString = new ArrayList<>();
            for (Routes route : routes) {
                routesString.add(route.getOriAdCode() + "," + route.getDstAdCode());
            }

            if (routesString.isEmpty()){
                routesString.add("abcdefghijklmn");
            }
            waybillQueryWrapper.lambda().in(Waybill::getOriAndDstAdCode,routesString);
        }
        //司机端显示所有运单（未确认报价）
        waybillQueryWrapper.lambda()
                .ne(Waybill::getDeliveryStatus,Constants.DeliveryStatus.CANCELLED)//未被取消
                .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.AWAIT_QUOTE)//待付定金
//                .and(wrapper -> wrapper
//                        .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.WAIT_QUOTE)//未报价
//                        .or()
//                        .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.AWAIT_QUOTE)//待付定金
//                )
                .orderByDesc(Waybill::getCreationTime);

        Page<Waybill> page = new Page<>(pageNum,pageSize);
        Page<Waybill> waybillPage = wayBillService.page(page, waybillQueryWrapper);


        Page<WAGParamVO> wagParamVOPage = wayBillService.waybillPageToWAGParamVOPage(waybillPage);


        //司机端 附带返回 本人对该订单的报价状态
        if (Constants.Role.DRIVER.equals(role)) {
            for (WAGParamVO wagParamVO : wagParamVOPage.getRecords()) {
                // 获取司机对该运单是否报价
                QueryWrapper<Quote> quoteQueryWrapper = new QueryWrapper<>();
                quoteQueryWrapper.lambda()
                        .eq(Quote::getWaybillId, wagParamVO.getWaybill().getId())
                        .eq(Quote::getDriverId, uid);
                Quote oneDB = quoteService.getOne(quoteQueryWrapper);
                if (oneDB != null) {
                    wagParamVO.setAlreadyQuote((short) 1);
                }else {
                    wagParamVO.setAlreadyQuote((short) 0);
                }
            }
        }

        return CommonResult.success(CommonPage.restPage(wagParamVOPage));
    }


    /**
     * 首页货源精准推荐
     */
    @PostMapping("driver/LoveWaybills")
    public CommonResult<CommonPage<WAGParamVO>> LoveWaybills(@RequestParam(defaultValue = "5") Integer pageSize,
                                                                     @RequestParam(defaultValue = "1") Integer pageNum, Short role){
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));

        QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
        routesQueryWrapper.lambda().eq(Routes::getUid,uid);
        List<Routes> routes = routesService.list(routesQueryWrapper);

        List<String> routesString = new ArrayList<>();
        for (Routes route : routes) {
            routesString.add(route.getOriAdCode() + "," + route.getDstAdCode());
        }

        if (routesString.isEmpty()){
            routesString.add("abcdefghijklmn");
        }
        System.out.println("routesString:"+routesString);
        QueryWrapper<Waybill> waybillQueryWrapper = new QueryWrapper<>();

        //司机端显示所有运单（未确认报价）
        waybillQueryWrapper.lambda()
                .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.AWAIT_QUOTE)//待付定金
                .ne(Waybill::getDeliveryStatus,Constants.DeliveryStatus.CANCELLED)//未被取消
                .in(Waybill::getOriAndDstAdCode,routesString)
                .orderByDesc(Waybill::getCreationTime);

        Page<Waybill> page = new Page<>(pageNum,pageSize);
        Page<Waybill> waybillPage = wayBillService.page(page, waybillQueryWrapper);


        Page<WAGParamVO> wagParamVOPage = wayBillService.waybillPageToWAGParamVOPage(waybillPage);


        //司机端 附带返回 本人对该订单的报价状态
        if (Constants.Role.DRIVER.equals(role)) {
            for (WAGParamVO wagParamVO : wagParamVOPage.getRecords()) {
                // 获取司机对该运单是否报价
                QueryWrapper<Quote> quoteQueryWrapper = new QueryWrapper<>();
                quoteQueryWrapper.lambda()
                        .eq(Quote::getWaybillId, wagParamVO.getWaybill().getId())
                        .eq(Quote::getDriverId, uid);
                Quote oneDB = quoteService.getOne(quoteQueryWrapper);
                if (oneDB != null) {
                    wagParamVO.setAlreadyQuote((short) 1);
                }else {
                    wagParamVO.setAlreadyQuote((short) 0);
                }
            }
        }

        return CommonResult.success(CommonPage.restPage(wagParamVOPage));
    }



    //司机报价QuoteController



    /**
     * （弃用）货主端根据运单id查询报价列表
     * @param id
     * @return
     */
//    @PostMapping("shiper/findQuoteByWaybillId")
//    public CommonResult<List<Quote>> findQuoteByWaybillId(@RequestParam Long id){
//        List<Quote> quoteByWaybill = wayBillMapper.findQuoteByWaybillId(id);
//        System.out.println(quoteByWaybill);
//        return CommonResult.success(quoteByWaybill);
//    }




    /**
     * 货主端筛选运单（创建订单时间（开始、结束） 订单车型 订单归属地）
     * @param beginTime
     * @param endTime
     * @param carType
     * @param place
     * @return
     */
    @GetMapping("shiper/queryWaybills")
    public CommonResult<CommonPage<WAGParamVO>> queryWaybills(@RequestParam String beginTime,
                                                  @RequestParam String endTime,
                                                  @RequestParam String carType,
                                                  @RequestParam String place,
                                                     @RequestParam Integer pageSize,
                                                     @RequestParam Integer pageNum){
        Long uid = Long.valueOf(BaseUserInfo.get("id"));
        LocalDateTime beginLDT = LocalDateTime.parse(beginTime);
        LocalDateTime endLDT = LocalDateTime.parse(endTime);

        // 创建分页对象
        Page<Waybill> page = new Page<>(pageNum, pageSize);
        Page<Waybill> waybillPage = wayBillMapper.findWaybillByPlaceAndCarType(page, uid,
                                                        beginLDT, endLDT, place, carType, pageSize, pageNum);


        Page<WAGParamVO> WAGParamVOPage = wayBillService.waybillPageToWAGParamVOPage(waybillPage);
        return CommonResult.success(CommonPage.restPage(WAGParamVOPage));
    }


    @Autowired
    private TmpAddressService tmpAddressService;
    @Autowired
    private AliSmsProperties aliSmsProperties;
    /**
     * 司机运输中
     */
    @RequestMapping (value = "/driver/pushTransStatus")
    public CommonResult<String> driverPushTransStatus(@RequestParam Long waybillId, @RequestParam String carNumber) throws Exception {

        Waybill waybill = wayBillService.getById(waybillId);
        waybill.setCarNumber(carNumber);
        waybill.setCardColor("2");//默认黄牌
        //在下面的service数据库更新waybill
        wayBillService.driverPushStatus(waybill, Constants.DeliveryStatus.TRANSPORTING);

        Long shiperId = waybill.getShiperId();
        User shiper = userService.getById(shiperId);
        Long driverId = waybill.getDriverId();
        User driver = userService.getById(driverId);
        Long shipAddressId = waybill.getShipAddressId();
        TmpAddress shipAddress = tmpAddressService.getById(shipAddressId);
        Long receiveAddressId = waybill.getReceiveAddressId();
        TmpAddress receiveAddress = tmpAddressService.getById(receiveAddressId);

        //调用阿里云接口，发送短信
//        systemMessageService.sendSmsMessage(shiper.getUserName(), shipAddress.getCity(), receiveAddress.getCity(),
//                    "发车", driver.getUserName(), waybill.getCarNumber());
        systemMessageService.sendSmsShipMessage(shiper.getUserName(),waybill.getWaybillNumber(), shipAddress.getCity(), receiveAddress.getCity(),
                    "发车", aliSmsProperties.getCustomerServicePhone(), waybill.getCarNumber());



        return CommonResult.success("司机运输中");
    }

    /**
     * 司机已送达
     */
    @RequestMapping (value = "/driver/pushDeliveredStatus")
    @Transactional
    public CommonResult<String> driverPushDeliveredStatus(@RequestParam Long waybillId,@RequestParam String receiptUrl) throws Exception {
        Waybill waybill = wayBillService.getById(waybillId);
        //卸货到达
        wayBillService.driverPushStatus(waybill,Constants.DeliveryStatus.DELIVERED);

        // 卸货到达，上传电子回单
        if (receiptUrl != null && !"".equals(receiptUrl)) {
            Waybill waybillDB = wayBillService.getById(waybillId);
            waybillDB.setReceiptUrl(receiptUrl);
            wayBillService.updateById(waybillDB);
        }else {
            throw new Exception("请上传回单");
        }


        /**
         * 司机的货物送达后，发送消息给货主
         */
        // 到付 月结 （正常播报
        if ( Constants.PayMethod.PAY_LATER.equals(waybill.getPayMethod()) || Constants.PayMethod.MONTHLY_PAYMENT.equals(waybill.getPayMethod())) {
            systemMessageService.SendMessageToShiperWhenWaybillFinish(waybill);
        }
        // 现付 （跳过播报
        else if (Constants.PayMethod.PAY_NOW.equals(waybill.getPayMethod())) {

        }

        return CommonResult.success("司机已送达");
    }




    /**
     * 货主  付定金\付运费（退回定金）
     * @param requestBody
     * @return
     * @throws Exception
     */
    @PostMapping (value = "/shiper/finishWaybill")
    public CommonResult<Map<String,String>> shiperFinishWaybill(@RequestBody Map<String,String> requestBody){
//        lock.lock();
        if (requestBody == null) {
            return CommonResult.failed("请求体不能为空");
        }

        // 使用 Map 的 getOrDefault 方法避免 null
        String code = requestBody.getOrDefault("code", "");

        Long waybillId = getLongFromRequestBody(requestBody, "id");

        // 确保 waybillId 不为 null
        if (waybillId == null ) {
            return CommonResult.failed("请求参数中 运单id 不能为空");
        }

        Waybill waybill = wayBillService.getById(waybillId);
        Short lock = waybill.getWaybillLock();
        if (Constants.WayBillLock.LOCK.equals(lock)) {
            throw new BaseException("此订单正被支付中");
        }

//        try {
            waybill.setWaybillLock(Constants.WayBillLock.LOCK);
        Long cuoId = waybill.getCuoId();
        log.info("cuoId:" + cuoId);
        CouponDet couponDet = couponDetService.getById(cuoId);
        if (!Objects.isNull(couponDet)) {
            if (Constants.WayBillLock.LOCK.equals(couponDet.getCouLock())) {
                throw new BaseException("优惠券已被使用");
            }else {
                couponDet.setCouLock(Constants.WayBillLock.LOCK);
                couponDetService.updateById(couponDet);
            }
            }
//            else {
//                waybill.setActAmount(waybill.getOfferAll());
//            }
            waybill.setPayType(Constants.WayBillPayType.SHIPFEE);
            wayBillService.updateById(waybill);
            // 金额类型，使用默认值 "deposit" 如果不存在
            String priceType = requestBody.getOrDefault("type", "offerEnd");

            // 平台类型，使用默认值 "app" 如果不存在
            String platform = requestBody.getOrDefault("platform", "mini");

        Map<String, String> dataMap = wayBillService.shiperSettleWaybill(code, waybillId, null, priceType, platform);

//        }finally {
//            lock.unlock();
//        }


        waybill.setPayTime(LocalDateTime.now());
        wayBillService.updateById(waybill);
        Long uid = waybill.getShiperId();
        int couponNum = couponDetService.getCouponDetNum(uid);
        User user = userService.getById(uid);
        user.setCouponNum(couponNum);
        userService.updateById(user);
        chatServer.onMessage(Constants.webSocket.WAYBILL.toString());

        return CommonResult.success(dataMap);
    }


    /**
     * 管理员取消运单(只更新运单状态) 退回定金
     * @param id
     * @return
     */
    @GetMapping("/admin/cancelWaybillById")
    public CommonResult adminCancelWaybill(@RequestParam String id) throws Exception {
        Long wid = Long.valueOf(id);
        wayBillService.adminCancelWaybill(wid);
        return CommonResult.success(null);
    }


    /**
     * 货主可开票
     * @param pageSize
     * @param pageNum
     * @return
     */

    @GetMapping("/WaybillsNeedInvoice")
//    public CommonResult<Map<String, List<WAGParamVO>>> WaybillsNeedInvoice(@RequestParam(defaultValue = "5") Integer pageSize,
    public CommonResult<Page> WaybillsNeedInvoice(@RequestParam(defaultValue = "5") Integer pageSize,
                                                                  @RequestParam(defaultValue = "1") Integer pageNum) {
        Long uid = Long.valueOf(BaseUserInfo.get("id"));

        Page<Waybill> objectPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Waybill> waybillQueryWrapper = new QueryWrapper<>();
        waybillQueryWrapper.lambda()
                .eq(Waybill::getShiperId,uid)
                .eq(Waybill::getWaybillStatus,Constants.WaybillStatus.SETTLED)
                .eq(Waybill::isNeedInvoiced,true)
                .eq(Waybill::isInvoiced,false)
                .orderByDesc(Waybill::getCreationTime);
//        System.out.println("size===================================:"+wayBillService.list(waybillQueryWrapper).size());
        Page<Waybill> waybillPage = wayBillService.page(objectPage, waybillQueryWrapper);
//        System.out.println("size:+++++++++++++++++++++++++++++"+waybillPage.getSize());
        long total = waybillPage.getTotal();
//        Page<WAGParamVO> wagParamVOPage = wayBillService.waybillPageToWAGParamVOPage(waybillPage);
        List<Waybill> WaybillRecords = waybillPage.getRecords();

//        Map<String, List<WAGParamVO>> result = waybillListToMap(WaybillRecords);

        List<WAGParamVO> wagParamVOS = new ArrayList<>();
        for (Waybill waybill : WaybillRecords){
            WAGParamVO wagParamVO = wayBillService.convertToWAGParamVO(waybill.getId());
            wagParamVOS.add(wagParamVO);
        }

//        wagParamVOS.
//        String size = String.valueOf(total);
//        HashMap<Object, Long> objectLongHashMap = new HashMap<>();
//        objectLongHashMap.put(wagParamVOS,total);


        Page<WAGParamVO> wagParamVOPage = new Page<>();
        wagParamVOPage.setTotal(total);
        wagParamVOPage.setRecords(wagParamVOS);
        // 返回封装好的结果
//        return CommonResult.success(result,size);
        return CommonResult.success(wagParamVOPage);
    }

    /**
     * 货主已开票
     * @param pageSize
     * @param pageNum
     * @return
     */

    @GetMapping("/WaybillsFinishInvoice")
//    public CommonResult<Map<String, List<Invoice>>> WaybillsFinishInvoice(@RequestParam(defaultValue = "5") Integer pageSize,
    public CommonResult<Page<Invoice>> WaybillsFinishInvoice(@RequestParam(defaultValue = "5") Integer pageSize,
                                                                    @RequestParam(defaultValue = "1") Integer pageNum) {
        Long uid = Long.valueOf(BaseUserInfo.get("id"));

        Page<Invoice> objectPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.lambda()
                .eq(Invoice::getUid,uid)
//                .eq(Waybill::isNeedInvoiced,true)
                .between(Invoice::getInvoiceState,Constants.invoiceState.APPLIED,Constants.invoiceState.RED)
                .orderByDesc(Invoice::getCreationTime);
        Page<Invoice> invoicePage = invoiceService.page(objectPage, invoiceQueryWrapper);
//        long total = invoicePage.getTotal();
//        Page<WAGParamVO> wagParamVOPage = wayBillService.waybillPageToWAGParamVOPage(waybillPage);
//        List<Invoice> invoiceList = invoicePage.getRecords();


//        Map<String, List<Invoice>> result = invoiceListToMap(invoiceList);
//        String size = String.valueOf(total);
        // 返回封装好的结果
        return CommonResult.success(invoicePage);
    }




    private Map<String, List<WAGParamVO>> waybillListToMap (List<Waybill> waybillList){
        Map<String, List<WAGParamVO>> result = new TreeMap<>(Comparator.reverseOrder());
        waybillList.forEach(waybill -> {
            LocalDateTime creationTime = waybill.getCreationTime();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String formattedDate = creationTime.format(formatter);

            // 将 Waybill 转换为 WAGParamVO
            WAGParamVO wagParamVO = wayBillService.convertToWAGParamVO(waybill.getId());

            // 将 WAGParamVO 添加到结果 Map 中，以格式化的日期为键
            result.computeIfAbsent(formattedDate, k -> new ArrayList<>()).add(wagParamVO);
        });
        return result;
    }

    private Map<String, List<Invoice>> invoiceListToMap (List<Invoice> invoiceList){
        Map<String, List<Invoice>> result = new TreeMap<>(Comparator.reverseOrder());
        invoiceList.forEach(invoice -> {
            LocalDateTime creationTime = invoice.getCreationTime();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String formattedDate = creationTime.format(formatter);

            // 将 WAGParamVO 添加到结果 Map 中，以格式化的日期为键
            result.computeIfAbsent(formattedDate, k -> new ArrayList<>()).add(invoice);
        });
        return result;
    }




}
